package ll.sms.factory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import ll.sms.db.SmsDataSource;
import ll.sms.exceptions.SmsDBException;
import ll.sms.util.SmsConfig;

public class ConnectionFactory {

	private static Connection getC3P0Connection() {
		try {
			if (SmsDataSource.getPool() == null) {
				SmsDataSource.initDataSource();
			}
			return SmsDataSource.getPool().getConnection();

		} catch (SQLException e) {
			e.printStackTrace();
			throw new SmsDBException(e);
		}
	}

	public static Connection getConnection(Parameters.Connection pc) {
		if (pc == Parameters.Connection.C3P0) {
			return getC3P0Connection();
		} else if (pc == Parameters.Connection.ORIGINAL) {
			return getOriginalConnection();
		}
		return null;
	}

	private static Connection getOriginalConnection() {
		try {
		String diverClass = SmsConfig.getProperties("db_driver");
		String url = SmsConfig.getProperties("db_uri");
		String username = SmsConfig.getProperties("db_username");
		String password = SmsConfig.getProperties("db_password");
		Class.forName(diverClass);
		Connection conn = DriverManager.getConnection(url,username,password);
		return conn;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		Connection conn = getConnection(Parameters.Connection.ORIGINAL);
		System.out.println(conn);
	}

}
